package com.sikulifang.bank.simulation.controller;

import cn.hutool.core.lang.Dict;
import cn.hutool.json.JSONUtil;
import com.sikulifang.bank.simulation.persistence.Bank;
import com.sikulifang.frequency.core.FrequencyContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * ClassName TestMain
 * Description
 *
 * @author Yat
 * Date 2023年7月12日, 0012 10:35
 * version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @Lazy
    @Resource
    private TestController testController;


    @PostMapping("/message")
    @ResponseBody
    public String message(@RequestBody Dict dict) {
        String json = JSONUtil.toJsonStr(dict.get("bank"));
        Bank bank = JSONUtil.toBean(json, Bank.class);
        return testController.handleMessage(bank, dict.getStr("message"));
    }

    public String handleMessage(Bank bank, String interfaceName) {

        FrequencyContext.setType(bank.getCode(), interfaceName);
        try {
            FrequencyContext.acquire();

            log.info("处理逻辑:'{}'", interfaceName);

            // FrequencyUtil.suspend(() -> (System.currentTimeMillis() - startTime) < 2000, 2000L);
        } catch (InterruptedException e) {
            log.error("调用频率过快:'{}'", interfaceName);
            return "Error";
        } finally {
            FrequencyContext.release(Boolean.TRUE);
        }
        return interfaceName;
    }

}
